package com.ubs.training.server.dao.impl.jdbc;

import com.ubs.training.server.dao.ContactTypeDao;
import com.ubs.training.server.dao.model.ContactType;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 5:39 AM
 * To change this template use File | Settings | File Templates.
 */
public class NamedParamContactTypeDaoImpl implements ContactTypeDao {
    private DataSource ds;
    private NamedParameterJdbcOperations ops;

    public DataSource getDs() {
        return ds;
    }

    public void setDs(DataSource ds) {
        this.ds = ds;
        ops = new NamedParameterJdbcTemplate(ds);
    }

    @Override
    public List<ContactType> getAll() {
        return ops.query("SELECT * FROM contact_type", Collections.EMPTY_MAP, new BeanPropertyRowMapper<ContactType>(ContactType.class));
    }

    @Override
    public ContactType getById(int id) {
        return ops.queryForObject("SELECT * FROM contact_type WHERE ID =:id", Collections.singletonMap("id", id), new BeanPropertyRowMapper<ContactType>(ContactType.class));
    }

    @Override
    public void add(ContactType t) {
        int id = ops.queryForInt("SELECT NEXT VALUE FOR cmstr_seq from dual", Collections.EMPTY_MAP);
        t.setId(id);

        ops.update("INSERT INTO CONTACT_TYPE VALUES ( :id, :ctype )", new BeanPropertySqlParameterSource(t));
    }

    @Override
    public void update(ContactType t) {
        ops.update("UPDATE contact_type SET ctype =:ctype WHERE id =:id", new BeanPropertySqlParameterSource(t));
    }

    @Override
    public void delete(int id) {
        ops.update("DELETE FROM contact_type WHERE id =:id",Collections.singletonMap("id", id));
    }

}
